import grails.converters.*

class PayPalController {
	
	String sometext

    def index = {
   		if(session.authenticatedUser == null) {
  			redirect(controller:'authentication', action:'index')
   		}
    }
    
	def prePayPal = {
    		def urlString = "https://api-3t.sandbox.paypal.com/nvp"
    		def API_user = "seller_1240120120_biz_api1.yahoo.com"
    		def API_password = "1240120139"
    		def signature = "AQpyLmWPJTGT-5qDSrk7sdgFKcEyA5KO3yabS4WhfjtV0b.Tyjtt4fZ9"
    		def version
    		def paymentaction
    		def amt = session.totalPrice
    		def returnURL
    		def cancelURL
    		def method
    		def queryString
    		def url
    		def connection
    		def writer
    		def outputResponse
    		def outputString
    		def token
    		def ack
    		
    		//PayPal Parsing #1
    		version = "2.3"
    		paymentaction = "Authorization"
    		returnURL = "http://localhost:8080/PictureCentral/shoppingCart/postPayPal"
    		cancelURL = "http://localhost:8080/PictureCentral/picture/list"
    		method = "SetExpressCheckout"
    		queryString = "USER=${API_user}&PWD=${API_password}&SIGNATURE=${signature}"
    		queryString += "&VERSION=${version}&PAYMENTACTION=${paymentaction}&AMT=${amt}"
    		queryString += "&RETURNURL=${returnURL}&CANCELURL=${cancelURL}&METHOD=${method}"		
    		url = new URL(urlString)
    		connection = url.openConnection()
    		connection.setRequestMethod("POST")
    		connection.doOutput = true
    		writer = new OutputStreamWriter(connection.outputStream)
    		writer.write(queryString)
    		writer.flush()
    		writer.close()
    		connection.connect()
    		outputResponse = connection.content.text
    		log.debug(outputResponse)
    		sometext = ""
    		outputString = outputResponse.split("&")
    		outputString.each {
    			if (it.startsWith("TOKEN")) {
    				token = URLDecoder.decode(it.replace('TOKEN=',''))
    			}
    			if (it.startsWith("ACK")) {
    				ack = it.replace('ACK=','')
    			}
    			//sometext += it + "\n"
    		}
    		sometext += "Parse#1: ACK = " + ack + "\n"
    		sometext += "Token = " + token + "\n"
    		
    		if (ack != "Success") {
    			sometext += "Authorization Error !!" + "\n"
    		}
    		else {
    			
    			url = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=${token}"
    			redirect(url: url)
    		}
    		//printText()
    	
    	}
    		
    	def postPayPal = {
    		def urlString = "https://api-3t.sandbox.paypal.com/nvp"
    		def API_user = "seller_1240120120_biz_api1.yahoo.com"
    		def API_password = "1240120139"
    		def signature = "AQpyLmWPJTGT-5qDSrk7sdgFKcEyA5KO3yabS4WhfjtV0b.Tyjtt4fZ9"
    		def version
    		def paymentaction
    		def amt = session.totalPrice
    		def method
    		def queryString
    		def url
    		def connection
    		def writer
    		def outputResponse
    		def outputString
    		def token
    		def ack
    		def payerid
    		def currencycode
    		
    		token = params.token
    		payerid = params.PayerID
    		
    		//PayPal Parsing #2
    		version = "2.3"
    		method = "GetExpressCheckoutDetails"
    		queryString = "USER=${API_user}&PWD=${API_password}&SIGNATURE=${signature}"
    		queryString += "&VERSION=${version}&TOKEN=${token}&METHOD=${method}"
    		url = new URL(urlString)
    		connection = url.openConnection()
    		connection.setRequestMethod("POST")
    		connection.doOutput = true
    		writer = new OutputStreamWriter(connection.outputStream)
    		writer.write(queryString)
    		writer.flush()
    		writer.close()
    		connection.connect()
    		outputResponse = connection.content.text
    		log.debug(outputResponse)
    		sometext = ""
    		outputString = outputResponse.split("&")
    		outputString.each {
    			if (it.startsWith("ACK")) {
    				ack = it.replace('ACK=','')
    			}
    			//sometext += it + "\n"
    		}
    		//sometext += "Parse#2: ACK = " + ack + "\n"
    		//sometext += "PayerID = " + payerid + "\n"

    		if (ack != "Success") {
    			sometext += "GetExpressCheckoutDetails Error !!" + "\n"
    		}
    		else {

    			//Parsing request #3
    			paymentaction = "Authorization"
    			method = "DoExpressCheckoutPayment"
    			queryString = "USER=${API_user}&PWD=${API_password}&SIGNATURE=${signature}"
    			queryString += "&VERSION=${version}&PAYMENTACTION=${paymentaction}"
    			queryString += "&PAYERID=${payerid}&TOKEN=${token}&AMT=${amt}&METHOD=${method}"		
    			url = new URL(urlString)
    			connection = url.openConnection()
    			connection.setRequestMethod("POST")
    			connection.doOutput = true
    			writer = new OutputStreamWriter(connection.outputStream)
    			writer.write(queryString)
    			writer.flush()
    			writer.close()
    			connection.connect()
    			outputResponse = connection.content.text
    			log.debug(outputResponse)

    			outputString = outputResponse.split("&")
    			outputString.each {
    				if (it.startsWith("ACK")) {
    					ack = it.replace('ACK=','')
    				}
    				if (it.startsWith("CURRENCYCODE")) {
    					currencycode = it.replace('CURRENCYCODE=','')
    				}
    				//sometext += it + "\n"
    			}

    			//sometext += "Parse#3: ACK = " + ack + "\n"
    				
    			if (ack != "Success") {
    				sometext += "DoExpressCheckoutPayment Error !!" + "\n"
    			}
    			else {
    				sometext += "Successfully paid " + amt + " " + currencycode + ". Thank you." + "\n"
    			}

    		}
    		printText()
    		
    		redirect(action:saveOrder)

    	}

    	def visaPayment = {
    		def urlString = "https://api-3t.sandbox.paypal.com/nvp"
    		def API_USER = "seller_1240120120_biz_api1.yahoo.com"
    		def API_PASSWORD = "1240120139"
    		def SIGNATURE = "AQpyLmWPJTGT-5qDSrk7sdgFKcEyA5KO3yabS4WhfjtV0b.Tyjtt4fZ9"
    		def VERSION = "56.0"
    		def PAYMENT_ACTION = "Authorization"
    		def AMT = session.totalPrice
    		def METHOD = "DoDirectPayment"
    		def creditcardtype = params.cardtype // now accept only "Visa"
    		def acct = params.acct //card1: 4109166586384522 //card2: 4772762828312697
    		def expdate = params.expiredmonth + params.expiredyear //card1: 052019 //card2: 012011
    		//def cvv2 = params.cvv2 //card1: don't know //card2: 000
    		def firstname = params.firstname //"Test"
    		def lastname = params.lastname //"User"
    		def street = params.address //"1 Main St"
    		def city = params.city //"San Jose"
    		def state = params.state //"CA"
    		def countrycode = params.countrycode //"US"
    		def zip = params.zipcode //"95131"
    		def currencycode = "USD" //params.currencyCode //"USD"
    		def queryString
       		def ack
      		def transactionid
       		def errors
    		def response = []
       		def nextUrl
    		queryString = "USER=${API_USER}&PWD=${API_PASSWORD}&SIGNATURE=${SIGNATURE}"
    		queryString += "&VERSION=${VERSION}&PAYMENTACTION=${PAYMENT_ACTION}&AMT=${AMT}"
    		queryString += "&METHOD=${METHOD}"
    		queryString += "&CREDITCARDTYPE=${creditcardtype}"
    		queryString += "&ACCT=${acct}"
    		queryString += "&EXPDATE=${expdate}"
    		//queryString += "&CVV2=${cvv2}"
    		queryString += "&FIRSTNAME=${firstname}&LASTNAME=${lastname}"
    		queryString += "&STREET=${street}&CITY=${city}&STATE=${state}&COUNTRYCODE=${countrycode}&ZIP=${zip}"
    		queryString += "&CURRENCYCODE=${currencycode}"		
    		//sometext = queryString
    		def url = new URL(urlString)
    		def connection = url.openConnection()
    		connection.setRequestMethod("POST")
    		connection.doOutput = true
    		def writer = new OutputStreamWriter(connection.outputStream)
    		writer.write(queryString)
    		writer.flush()
    		writer.close()
    		connection.connect()
    		def outputResponse = connection.content.text
    		log.debug(outputResponse)
    		//print outputResponse + "\n"
    		def outputString = outputResponse.split("&")
    		outputString.each {
    			if (it.startsWith("ACK")) {
    				ack = it.replace('ACK=','')
    			}
    			if (it.startsWith("TRANSACTIONID")) {
    				transactionid = it.replace('TRANSACTIONID=','')
    			}
    			if (it.startsWith("L_LONGMESSAGE0")) {
    				errors = URLDecoder.decode(it.replace('L_LONGMESSAGE0=',''))
    			}
    		}
			if (ack != "Success") {
				response = [success:false, errors:errors]
			} else {
				
				def AUTHORIZATIONID = transactionid
				def COMPLETETYPE = "Complete"
				METHOD = "DoCapture"
				AMT = session.totalPrice
	    		queryString = "USER=${API_USER}&PWD=${API_PASSWORD}&SIGNATURE=${SIGNATURE}"
        		queryString += "&VERSION=${VERSION}&METHOD=${METHOD}"
        		queryString += "&AUTHORIZATIONID=${AUTHORIZATIONID}&COMPLETETYPE=${COMPLETETYPE}"
        		queryString += "&AMT=${AMT}&CURRENCYCODE=${currencycode}"		
        		url = new URL(urlString)
	        	connection = url.openConnection()
	        	connection.setRequestMethod("POST")
	        	connection.doOutput = true
	        	writer = new OutputStreamWriter(connection.outputStream)
	        	writer.write(queryString)
	        	writer.flush()
	        	writer.close()
	        	connection.connect()
	        	outputResponse = connection.content.text
	        	log.debug(outputResponse)
	        	outputString = outputResponse.split("&")
	        	outputString.each {
	        		if (it.startsWith("ACK")) {
	        			ack = it.replace('ACK=','')
	        		}
	        		if (it.startsWith("TRANSACTIONID")) {
	        			transactionid = it.replace('TRANSACTIONID=','')
	        		}
	        		if (it.startsWith("L_LONGMESSAGE0")) {
	        			errors = URLDecoder.decode(it.replace('L_LONGMESSAGE0=',''))
	        		}
	        	}
				def orderParams = [name: "${params.firstname} ${params.lastname}", address: "${params.address}", city: "${params.city}", state:"${params.state}", zipcode:"${params.zipcode}", paymentDetail:"${params.cardtype}"];
				redirect(controller:'shoppingCart', action:'saveOrder', params:orderParams)
			}
    	}
   
}
